﻿//------------------------------------------------------------------------------
//  Namespace: FruitVentDesign.Utils
//  
//  Function： N/A
//  Name： CommonUtil
//  
//  Ver       Time                     Author
//  0.10      2021/6/23 18:28:39      Benedict Deng
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
using System.Windows.Media;

namespace FruitVentDesign.Utils
{
    public class CommonUtil
    {
        /// <summary>
        /// 在可视化树中搜索特定类型的元素。
        /// </summary>
        /// <typeparam name="T">元素类型</typeparam>
        /// <param name="visual">父元素.</param>
        /// <returns></returns>
        public static T FindVisualChild<T>(Visual visual) where T : Visual
        {
            for (int i = 0; i < VisualTreeHelper.GetChildrenCount(visual); i++)
            {
                Visual child = (Visual)VisualTreeHelper.GetChild(visual, i);
                if (child != null)
                {
                    if (child is T correctlyTyped)
                    {
                        return correctlyTyped;
                    }

                    T descendent = FindVisualChild<T>(child);
                    if (descendent != null)
                    {
                        return descendent;
                    }
                }
            }

            return null;
        }
    }
}
